/**
 * axios封装
 */
import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { GlobalLoading } from './message'
import { msgInfoEl } from '.'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // 跨域时发送cookie
    timeout: 120000 // request timeout
})
const loading = new GlobalLoading()
service.interceptors.request.use(config => {
    if (config?.showLoading) {
        loading.show()
    }
    // const isToken = (config.headers || {}).isToken === false
    // iframe嵌套存储不到cookies里面 改用sessiontLocal
    // const sessionLocal = window.sessionStorage.getItem('systoken')
    // console.log(sessionLocal, getToken(), 'TOKEN')
    // if (sessionLocal || getToken() && !isToken) {
    // config.headers['sysToken'] = getToken() || sessionLocal // 让每个请求携带自定义token 请根据实际情况自行修改
    // } else {
    // config.headers['sysToken'] = 'c64dd4dac160904f76a09c81b078228a' // token不要写死
    // config.headers['Referrer-Policy'] = 'unsafe-url' // 表头跨越限制 暂时没用
    // }
    config.headers['sysToken'] = window.sessionStorage.getItem('china-tower-token-pms20')
    // console.log(router.currentRoute.query)
    // const isPms10 = !!router.currentRoute.query?.token
    // if (isPms10) {
    //   config.headers['sysToken'] = getToken10()
    // }
    return config
},
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use((response) => {
    if (response.config?.showLoading) {
        loading.hide()
    }
    if (response.data == null && response.config.responseType === 'json' && response.request.responseText != null) {
        try {
            // eslint-disable-next-line no-param-reassign
            response.data = JSON.parse(response.request.responseText)
        } catch (e) {
            // ignored
        }
    }
    const res = response.data
    if (response.status === 500 && !response.config.hideMessage) {
        return msgInfoEl({
            message: response.message || '操作异常',
            type: 'error'
        })
    }
    if (res instanceof Blob) {
        return response
    }
    if (response.status !== 200 || +res.code !== 200) {
        if (res instanceof Blob) {
            return response
        }
        !response.config?.hideMessage && msgInfoEl({
            message: res.message || '操作异常',
            type: 'error'
        })
        return res
    }
    return res
},
    error => {
        if (error?.response?.config?.showLoading) {
            loading.hide()
        }
        try {
            const data = error.response.data
            if (data.error === 'unauthorized_client' || error.response.status === '401') {
                if (!getToken()) { return }
                removeToken()
                router.push({ path: '/fail' })
                msgInfoEl({
                    message: '您的登录已过期，请重新登录',
                    type: 'error'
                })
            } else {
                msgInfoEl({
                    message: data.message || '操作异常',
                    type: 'error'
                })
            }
        } catch (err) {
            console.log(err)
        }
        return Promise.reject(error.message)
    }
)

export default service
